#include "A_Config.h"
static lv_obj_t *obj_menu = NULL;
static lv_obj_t *selected = NULL;
static int16_t selected_num = 0;
static int16_t total = 0;
bool started = false;
static void btn_event_cb(lv_event_t *e)
{
    if(started == false)return;
    started = false;
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *btn = lv_event_get_target(e);
    if (code == LV_EVENT_CLICKED)
    {
        selected = btn;
    }
}
void menu_create(void)
{
    LOCKLV();
    obj_menu = lv_obj_create(lv_layer_top());
    lv_obj_set_size(obj_menu, 250, 180);
    lv_obj_set_pos(obj_menu, (screenWidth - 250) / 2, (screenHeight - 180) / 2);
    lv_obj_set_style_opa(obj_menu, 0, 0);
    lv_obj_set_flex_flow(obj_menu, LV_FLEX_FLOW_ROW_WRAP);
    UNLOCKLV();
    total = 0;
    menu_add(LV_SYMBOL_LEFT "  返回");
    selected = NULL;
    started = false;
}

/**
 *
 * @brief 添加菜单项
 * @param str 项目名称
 * @return 无
 */
void menu_add(const char *str)
{
    if (obj_menu == NULL)
        return;
    LOCKLV();
    lv_obj_t *btn = lv_btn_create(obj_menu);
    // lv_obj_set_width(btn, lv_pct(50));

    lv_obj_t *label = lv_label_create(btn);
    lv_label_set_long_mode(label, LV_LABEL_LONG_SCROLL_CIRCULAR);
    lv_obj_set_style_text_font(label, &lv_font_chinese_16, 0);
    lv_label_set_text_fmt(label, str);
    lv_obj_fade_in(btn, 300, 0);
    lv_obj_add_event_cb(btn, btn_event_cb, LV_EVENT_CLICKED, NULL);
    UNLOCKLV();
    ++total;
}

static int16_t menu_get_selected()
{
    if (selected == NULL)
        return -1;
    lv_obj_t *b;
    for (uint16_t i = 0; i < total; ++i)
    {
        b = lv_obj_get_child(obj_menu, i);
        if (selected == b)
            return i;
    }
    return -1;
}

bool menu_handle()
{
    if (selected != NULL)
    {
        LOCKLV();
        lv_obj_fall_down(obj_menu, 30, 300);
        UNLOCKLV();
        selected_num = menu_get_selected();
        vTaskDelay(370 / portTICK_PERIOD_MS);
        LOCKLV();
        lv_obj_del(obj_menu);
        UNLOCKLV();
        selected = NULL;
        return true;
    }
    vTaskDelay(30 / portTICK_PERIOD_MS);
    return false;
}

void menu_display()
{
    selected_num = 0;
    LOCKLV();
    lv_obj_pop_up(obj_menu);
    UNLOCKLV();
    selected = NULL;
    started = true;
}

int16_t menu_show()
{
    menu_display();
    while (1)
    {
        if (menu_handle())
        {
            break;
        }
    }
    return selected_num;
}
